"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.PullDownRefreshMiniLayout = void 0;

var _react = _interopRequireWildcard(require("react"));

var _components = require("@tarojs/components");

var _classnames = _interopRequireDefault(require("classnames"));

var _configContext = require("../../../extends/configContext");

var _util = require("./util");

var _excluded = ["damping", "onRefresh", "isFinished", "children", "height", "status", "isReachTop", "isScrollView"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

var PullDownRefreshMiniLayout = function PullDownRefreshMiniLayout(_ref) {
  var _ref$damping = _ref.damping,
      damping = _ref$damping === void 0 ? 80 : _ref$damping,
      _ref$onRefresh = _ref.onRefresh,
      onRefresh = _ref$onRefresh === void 0 ? function () {} : _ref$onRefresh,
      isFinished = _ref.isFinished,
      children = _ref.children,
      height = _ref.height,
      status = _ref.status,
      isReachTop = _ref.isReachTop,
      isScrollView = _ref.isScrollView,
      props = _objectWithoutProperties(_ref, _excluded);

  var _useConfig = (0, _configContext.useConfig)(),
      clsPrefix = _useConfig.clsPrefix; // touch数据


  var _useState = (0, _react.useState)(''),
      _useState2 = _slicedToArray(_useState, 2),
      loadingText = _useState2[0],
      setLoadingText = _useState2[1];

  var _useState3 = (0, _react.useState)({
    height: '0',
    overflowY: 'auto',
    overflowX: 'hidden'
  }),
      _useState4 = _slicedToArray(_useState3, 2),
      style = _useState4[0],
      setStyle = _useState4[1];

  var reachTop = (0, _react.useRef)(true);
  var loading = (0, _react.useRef)();
  var startY = (0, _react.useRef)(0);
  var endY = (0, _react.useRef)(0);
  (0, _react.useEffect)(function () {
    setStyle(_objectSpread(_objectSpread({}, style), {}, {
      height: "".concat(parseInt(height), "px"),
      overflowY: 'auto',
      overflowX: 'hidden'
    }));
  }, [height]);
  (0, _react.useEffect)(function () {
    if (isFinished) {
      setLoadingText('');
      endY.current = 0;
      setStyle(_objectSpread(_objectSpread({}, style), {}, {
        marginTop: 0,
        transition: 'all 0.3s'
      }));
    }
  }, [isFinished]);

  var onTouchStart = function onTouchStart(e) {
    var _e$touches = e.touches;
    _e$touches = _e$touches === void 0 ? [] : _e$touches;

    var _e$touches2 = _slicedToArray(_e$touches, 2),
        _e$touches2$ = _e$touches2[0],
        touche = _e$touches2$ === void 0 ? {} : _e$touches2$,
        _ = _e$touches2[1];

    startY.current = touche.pageY;
  };

  var onTouchMove = function onTouchMove(e) {
    var _e$touches3 = e.touches;
    _e$touches3 = _e$touches3 === void 0 ? [] : _e$touches3;

    var _e$touches4 = _slicedToArray(_e$touches3, 2),
        _e$touches4$ = _e$touches4[0],
        touche = _e$touches4$ === void 0 ? {} : _e$touches4$,
        _ = _e$touches4[1];

    endY.current = touche.pageY; // < 0 说明向下移动

    var diff = startY.current - touche.pageY; // 判断子元素是否触顶

    var isBool = isScrollView ? isReachTop : reachTop;

    if (diff < 0 && isBool) {
      (0, _util.preventDefault)(e);
      Math.abs(diff) > 40 ? setLoadingText('松手立即刷新') : setLoadingText('下拉可以刷新');
      var marginTop = Math.abs(diff) > damping ? "".concat(damping / 2, "px") : "".concat(Math.abs(diff) / 2, "px");
      setStyle(_objectSpread(_objectSpread({}, style), {}, {
        marginTop: marginTop,
        transition: 'all 0.3s'
      }));
    }
  };

  var onTouchEnd = function onTouchEnd() {
    var marginTop = style.marginTop; // < 0 说明向下移动

    var diff = startY.current - endY.current; // 判断子元素是否触顶

    var isBool = isScrollView ? isReachTop : reachTop;

    if (diff <= -40 && isBool) {
      // 只有向下才可以刷新
      if (Math.abs(diff) < damping) {
        marginTop = "".concat(Math.abs(diff) / 2, "px");
      } else {
        marginTop = "".concat(damping / 2, "px");
      }

      setLoadingText('正在刷新');
      onRefresh();
    } else if (0 > diff && diff > -40) {
      // 下拉幅度不够，没有触发下拉刷新
      setLoadingText('');
      marginTop = 0;
    } else {
      setLoadingText('');
    }

    setStyle(_objectSpread(_objectSpread({}, style), {}, {
      marginTop: marginTop
    }));
  };

  var renderStatus = function renderStatus() {
    if (status) {
      return status;
    }

    return /*#__PURE__*/_react.default.createElement(_components.View, {
      className: (0, _classnames.default)("".concat(clsPrefix, "-pull-refresh__loading")),
      ref: loading
    }, loadingText);
  };

  var onScroll = function onScroll(e) {
    var _e$detail = e.detail;
    _e$detail = _e$detail === void 0 ? {} : _e$detail;
    var _e$detail$scrollTop = _e$detail.scrollTop,
        scrollTop = _e$detail$scrollTop === void 0 ? 0 : _e$detail$scrollTop;
    reachTop.current = scrollTop <= 0;
  };

  var List = isScrollView ? _components.View : _components.ScrollView;
  return /*#__PURE__*/_react.default.createElement(_components.View, {
    className: (0, _classnames.default)("".concat(clsPrefix, "-pull-refresh"))
  }, renderStatus(), /*#__PURE__*/_react.default.createElement(List, _extends({
    scrollY: true,
    style: style,
    className: (0, _classnames.default)("".concat(clsPrefix, "-pull-refresh__list")),
    onTouchStart: onTouchStart,
    onTouchEnd: onTouchEnd,
    onTouchMove: onTouchMove,
    onTouchCancel: onTouchEnd,
    onScroll: onScroll
  }, props), children));
};

exports.PullDownRefreshMiniLayout = PullDownRefreshMiniLayout;